<?php

namespace App\Service\CommodityService;

use App\Service\BaseService;
use App\Model\CommodityModel\SupplierCompany;
use Service\AppService\IdService;
use App\Model\CommodityModel\WarehouseInfo;
use App\Model\CommodityModel\Brandinfo;
use App\Model\CommodityModel\Classifyinfo;
use App\Model\CommodityModel\Countryinfo;
use App\Model\CommodityModel\CommoditySpu;
use Hyperf\DbConnection\Db;
use App\Model\CommodityModel\CommodityArchives;
use App\Model\CommodityModel\CommodityDescription;
use App\Model\CommodityModel\CommoditySpecAttr;
use App\Model\CommodityModel\CommoditySpecValue;
use App\Model\CommodityModel\CommoditySpecGroup;
use App\Model\CommodityModel\Unitinfo;
use App\Model\CommodityModel\SupplierCommodity;
use App\Model\CommodityModel\Stockinfo;
use App\Model\CommodityModel\CommodityGroupAttr;
use App\Service\Code\Normal;
use App\Service\HttpRequest\Http;
use App\Service\TaskServer\TaskWorker;

class SyncBdGoodsMixInfoService extends BaseService 
{

    public function getDoPost(string $start_date,string $end_date) 
    {
        $filter = [
            'filter'    => [
                [
                    'key'   => 'updateTime',
                    'value' => $start_date,
                    'by'    => 'ge'
                ],
                [
                    'key'   => 'updateTime',
                    'value' => $end_date,
                    'by'    => 'le'
                ]
            ]
        ];
        
        $filter = json_encode($filter,JSON_UNESCAPED_UNICODE);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL             => 'https://admin.bd-ego.com/admin/api/v1/product/getGoodsInfo',
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_ENCODING        => '',
            CURLOPT_MAXREDIRS       => 10,
            CURLOPT_TIMEOUT         => 0,
            CURLOPT_FOLLOWLOCATION  => true,
            CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST   => 'POST',
            CURLOPT_POSTFIELDS      => $filter,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Cookie: SameSite=None; Secure=true; name=value'
            ),
        ));
        
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    
    /**
     * ['updateTimeStart' => $updateTimeStart, 'updateTimeEnd' => $updateTimeEnd]
     * 原符号       <       <=      >       >=      <>
     * 对应函数    lt()     le()    gt()    ge()    ne()
     */
    public function sync($param) 
    {
        //开始推送数据
        $response  = $this->getDoPost($param["updateTimeStart"], $param["updateTimeEnd"]);
        $result    = json_decode($response,true);
        if (!isset($result['data']) || empty($result['data'])) {
            return Normal::returnCode(Normal::FAIL, '无数据处理1', $result);
        }
        if (!isset($result['data']['list']) || empty($result['data']['list'])) {
            return Normal::returnCode(Normal::FAIL, '无数据处理2', $result);
        }
        
        echo count($result['data']['list']).PHP_EOL;
        $handleNum   = 0;
        $bdSpuIdsArr = [];
        $list        = $result['data']['list'];
        foreach ($list as $item) {
            $skuList = $item['skuList'] ?? [];
            if (empty($skuList)) {
                continue;
            }
            
            echo "开始更新分类\r\n";
            //处理分类
            $resClass          = $this->handleClass($item);
            $second_class_id   = $resClass['second_class_id'];
            $second_class_name = $resClass['second_class_name'];
            $third_class_id    = $resClass['third_class_id'];
            $third_class_name  = $resClass['third_class_name'];
            
            
            //处理图片和详情
            echo "开始处理图片和详情\r\n";
            $resImg = $this->formatImgAndDesc($item);

            foreach ($skuList as $skuRow) 
            {
                //处理供应商和仓库
                echo "开始处理供应商和仓库\r\n";
                $res1         = $this->handleWarehouseAndSupplierCompany($skuRow);
                $warehouse_id = $res1['warehouse_id'];//仓库id
                $supplier_id  = $res1['supplier_id'];//供应商id
                //处理品牌关联
                echo "开始处理品牌关联\r\n";
                $res2     = $this->handleBrand($skuRow);
                $brand_id = $res2['brand_id'];//品牌id
                //处理国家
                echo "开始处理国家\r\n";
                $res3       = $this->handleCountry($skuRow);
                $country_id = $res3['country_id'];//国家id
                //处理单位
                echo "开始处理单位\r\n";
                $res4    = $this->handleUnit($skuRow);
                $unit_id = $res4['unit_id'];//单位id
                //处理spu
                echo "开始处理spu\r\n";
                $res5   = $this->handleSpu($skuRow);
                $spu_id = $res5['spu_id'];//spu id
                //处理spec和specValue
                echo "开始处理spec和specValue\r\n";
                $resSpuSpec     = $this->handleSpuSpec($skuRow);
                $spec_attr_ids  = $resSpuSpec['spec_attr_ids'];
                $spec_value_str = $resSpuSpec['spec_value_str'];
                $value_name_str = $resSpuSpec['value_name_str'];
                //处理商品主资料信息
                echo "开始处理商品主资料信息\r\n";
                $goodsBasic = [
                    'second_class_id' => $second_class_id,
                    'third_class_id'  => $third_class_id,
                    'brand_id'        => $brand_id,
                    'country_id'      => $country_id,
                    'unit_id'         => $unit_id,
                    'spu_id'          => $spu_id,
                    'images'          => $resImg['images'],
                    'desc'            => $resImg['desc'],
                    'spec_value_str'  => $spec_value_str,
                    'value_name_str'  => $value_name_str,
                ];
                $res6       = $this->handleGoodsBasic($skuRow, $item, $goodsBasic);
                $goods_id   = $res6['goods_id'];//商品主资料id
                $isComplete = $res6['is_complete'];//商品主资料是否完整
                //处理商品主资料图片和详情信息
                $goodsDetail = [
                    'goods_id' => $goods_id,
                    'hasImage' => $resImg['hasImage'],
                    'images'   => $resImg['images'],
                    'hasDesc'  => $resImg['hasDesc'],
                    'desc'     => $resImg['desc'],
                ];
                echo "开始处理商品主资料图片和详情信息\r\n";
                $this->handleGoodsDetail($goodsDetail);
                //处理供应商商品
                $supGoodsInfo      = [
                    'goods_desc'        => $resImg['desc'],
                    'goods_uinit'       => $res4['unit_name'],
                    'goods_brand'       => $res2['brand_name'],
                    'goods_third_class' => $third_class_name,
                    'goods_country'     => $res3['country_name'],
                    'goods_image'       => $resImg['images'],
                    'supplier_id'       => $supplier_id,
                    'goods_id'          => $goods_id,
                ];
                
                echo "开始处理处理供应商商品\r\n";
                $res7              = $this->handleSupplierGoods($skuRow, $item, $supGoodsInfo);
                $supplier_goods_id = $res7['supplier_goods_id'];
                //处理供应商商品库存
                $stockInfo = [
                    'supplier_id'       => $supplier_id,
                    'goods_id'          => $goods_id,
                    'supplier_goods_id' => $supplier_goods_id,
                    'warehouse_id'      => $warehouse_id
                ];
                //处理供应商商品库存
                echo "开始处理处理供应商商品库存\r\n";
                $this->handleSupplierGoodsStock($skuRow, $item, $stockInfo);
                //处理spec_group
                $specGroup     = [
                    'spu_id'         => $spu_id,
                    'third_class_id' => $third_class_id
                ];
                echo "开始处理处理spec_group\r\n";
                $res8          = $this->handleSpecGroup($skuRow, $specGroup);
                $spec_group_id = $res8['spec_group_id'];
                //处理group_attr
                $groupAttr = [
                    'spec_group_id' => $spec_group_id,
                    'spec_attr_ids' => $spec_attr_ids,
                ];
                
                echo "开始处理处理group_attr\r\n";
                $this->handleGroupAttr($groupAttr);
                //获取所有百大SPUID
                array_push($bdSpuIdsArr, $skuRow['upcVo']['spu']['spuId']);
                //如果商品资料齐全，则需要向MQ发送资料变更消息
                echo "开始处理处理MQ发送资料变更消息\r\n";
                if ($isComplete) {
                    CommodityStockService::instance()->publish([(string)$goods_id]);
                }
                $handleNum += 1;
            }
        }
        if ($bdSpuIdsArr) {
            //处理主资料的 SpuDefault 字段
            echo "开始处理处理SpuDefault\r\n";
            $bdSpuIdsArr = array_unique($bdSpuIdsArr);
            // SELECT BD_SPU_ID, MIN(ID) as ID FROM commodityarchives_s2b WHERE BD_SPU_ID>0  GROUP BY BD_SPU_ID
            $need = CommodityArchives::where('BD_SPU_ID', '>', 0)->whereIn('BD_SPU_ID', $bdSpuIdsArr)->selectRaw('BD_SPU_ID, MIN(ID) as min_id')->groupBy('BD_SPU_ID')->get()->toArray();
            if ($need) {
                CommodityArchives::instance()->whereIn('BD_SPU_ID', array_column($need, 'BD_SPU_ID'))->update(['SpuDefault' => 0]);
                CommodityArchives::instance()->whereIn('ID', array_column($need, 'min_id'))->update(['SpuDefault' => 1]);
            }
        }
        return Normal::returnCode(Normal::SUC, '处理完成,同步数量：' . $handleNum);
    }

    /**
     * 处理供应商商品库存
     * @param $skuRow
     * @param $item
     * @param $stockInfo
     */
    public function handleSupplierGoodsStock($skuRow, $item, $stockInfo) {
        $where       = [
            //['SupplierCompanyID', '=', $stockInfo['supplier_id']],
            //['CommodityArchivesID', '=', $stockInfo['goods_id']],
            ['SupplierCommodityID', '=', $stockInfo['supplier_goods_id']],
            //['WarehouseID', '=', $stockInfo['warehouse_id']],
            ['BatchNo', '=', '基准批次'],
        ];
        $ycStockInfo = Stockinfo::instance()->info($where);
        $specList    = [];
        $priceArr    = [];
        $BdSpecList  = array_column($skuRow['skuOtherCountInfoList'], null, 'count');
        foreach ($BdSpecList as $v) {
            //菜鸟如果当前这个数据，规格数据不是 1 规格的 ，就跳过不要了
            if($skuRow['depot']['pushWmsType'] == 'CN' && $v['count'] != 1){
                continue;
            }
            $specList[] = [
                'SpecificationNum'          => (string)$v['count'],
                'SpecificationPrice'        => (string)$v['allCostPrice'],
                'SpecificationFreightPrice' => (string)$v['allCostPrice'],
            ];
            $priceArr[] = bcdiv((string)$v['allCostPrice'], (string)$v['count'], 2);
        }
        $batchSpecMinSinglePrice = $priceArr ? min($priceArr) : 0;
        $batchSpecMaxSinglePrice = $priceArr ? max($priceArr) : 0;
        if ($ycStockInfo) {
            //更新
            $update = [
                'UpdateTime'              => date("Y-m-d H:i:s"),
                'Number'                  => $skuRow['skuStock']['availableStock'],
                'BatchSpecMinSinglePrice' => $batchSpecMinSinglePrice,
                'BatchSpecMaxSinglePrice' => $batchSpecMaxSinglePrice,
                'IsHasPrice'              => $batchSpecMinSinglePrice > 0 ? 1 : 0,
                'SpecList'                => json_encode($specList, JSON_UNESCAPED_UNICODE),
                'SupplierCompanyID'       => $stockInfo['supplier_id'],
                'CommodityArchivesID'     => $stockInfo['goods_id'],
                'WarehouseID'             => $stockInfo['warehouse_id'],
            ];
            Stockinfo::instance()->where('ID', $ycStockInfo['ID'])->update($update);
        } else {
            //新增
            $data = [
                'ID'                      => IdService::instance()->getOtherID(),
                'CreateTime'              => date("Y-m-d H:i:s"),
                'UpdateTime'              => date("Y-m-d H:i:s"),
                'IsDeleted'               => 0,
                'Number'                  => $skuRow['skuStock']['availableStock'],
                'BatchNo'                 => '基准批次',
                'BatchSpecMinSinglePrice' => $batchSpecMinSinglePrice,
                'BatchSpecMaxSinglePrice' => $batchSpecMaxSinglePrice,
                'IsHasPrice'              => $batchSpecMinSinglePrice > 0 ? 1 : 0,
                'SpecList'                => json_encode($specList, JSON_UNESCAPED_UNICODE),
                'SupplierCompanyID'       => $stockInfo['supplier_id'],
                'CommodityArchivesID'     => $stockInfo['goods_id'],
                'SupplierCommodityID'     => $stockInfo['supplier_goods_id'],
                'WarehouseID'             => $stockInfo['warehouse_id'],
            ];
            Stockinfo::instance()->add($data);
        }
    }

    /**
     * 处理供应商商品
     * @param $skuRow
     * @param $item
     * @param $supGoodsInfo
     */
    public function handleSupplierGoods($skuRow, $item, $supGoodsInfo) {
        $imagesStr       = $supGoodsInfo['goods_image'] ?? '';
        $imagesArr       = $imagesStr ? json_decode($imagesStr, true) : [];
        $images          = $imagesArr ? array_column($imagesArr, 'ImageUrl') : [];
        $ycSupplierGoods = SupplierCommodity::instance()->info(['SupplierCommoditySkuCode' => $skuRow['wmsSkuCode']]);
        if ($ycSupplierGoods) {
            //更新
            $update = [
                'TaxRate'                             => $item['taxRate'] ? $item['taxRate'] : '0.000',
                'SupplierCommodityDescription'        => $supGoodsInfo['goods_desc'],
                'SupplierCommodityUinit'              => $supGoodsInfo['goods_uinit'],
                'SupplierCommodityBrand'              => !empty($supGoodsInfo['goods_brand']) ? $supGoodsInfo['goods_brand'] : '',
                'SupplierCommodityClassify'           => $supGoodsInfo['goods_third_class'],
                'SupplierCommodityOriginPlace'        => !empty($supGoodsInfo['goods_country']) ? $supGoodsInfo['goods_country'] : '暂无',
                'SupplierCommodityInternationBarCode' => $skuRow['upcVo']['upc'],
                'SupplierCommodityType'               => $this->getGoodsType($skuRow['depot']['attribute']),
                'SupplierCommodityImageUrl'           => json_encode($images, JSON_UNESCAPED_UNICODE),
                'SupplierCompanyID'                   => $supGoodsInfo['supplier_id'],
                'SupplierCommoditySkuCode'            => $skuRow['wmsSkuCode'],
                'SupplierCommodityName'               => $skuRow['count'] > 1 ? $skuRow['upcName'] : $item['productName'],
                'SupplierCommodityKey'                => isset($skuRow['itemNo']) && !empty($skuRow['itemNo']) ? $skuRow['itemNo'] : $skuRow['wmsSkuCode'],
                'SupplierCommodityNetWeight'          => $skuRow['upcVo']['netWeight'] ?? '0.000',
                'SaleType'                            => $item['putAway'] == 'UP' ? 0 : 1,
                'SKUCode'                             => $skuRow['skuCode'],
                'CommodityArchivesID'                 => $supGoodsInfo['goods_id'],
                'HSCode'                              => $skuRow['hsCode'],
                //'IsHaveTaxRate'                       => $item['freeTax'] == 'Y' ? 1 : 0,
                'IsHaveTaxRate'                       => 0,//都写为不含税模式
                'UpstreamSaleType'                    => $item['putAway'] == 'UP' ? 1 : 0,
                'UpdateTime'                          => date('Y-m-d H:i:s')
            ];
            SupplierCommodity::instance()->where('ID', $ycSupplierGoods['ID'])->update($update);
            return ['supplier_goods_id' => $ycSupplierGoods['ID']];
        }
        //新增
        $data = [
            'CreateTime'                          => date("Y-m-d H:i:s"),
            'ID'                                  => IdService::instance()->getOtherID(),
            'TaxRate'                             => $item['taxRate'] ? $item['taxRate'] : '0.000',
            'SupplierCommodityDescription'        => $supGoodsInfo['goods_desc'],
            'SupplierCommodityUinit'              => $supGoodsInfo['goods_uinit'],
            'SupplierCommodityBrand'              => !empty($supGoodsInfo['goods_brand']) ? $supGoodsInfo['goods_brand'] : '',
            'SupplierCommodityClassify'           => $supGoodsInfo['goods_third_class'],
            'SupplierCommodityOriginPlace'        => !empty($supGoodsInfo['goods_country']) ? $supGoodsInfo['goods_country'] : '暂无',
            'SupplierCommodityInternationBarCode' => $skuRow['upcVo']['upc'],
            'SupplierCommodityType'               => $this->getGoodsType($skuRow['depot']['attribute']),
            'SupplierCommodityImageUrl'           => json_encode($images, JSON_UNESCAPED_UNICODE),
            'SupplierCompanyID'                   => $supGoodsInfo['supplier_id'],
            'SupplierCommoditySkuCode'            => $skuRow['wmsSkuCode'],
            'SupplierCommodityName'               => $skuRow['count'] > 1 ? $skuRow['upcName'] : $item['productName'],
            'SupplierCommodityKey'                => isset($skuRow['itemNo']) && !empty($skuRow['itemNo']) ? $skuRow['itemNo'] : $skuRow['wmsSkuCode'],
            'SupplierCommodityNetWeight'          => $skuRow['upcVo']['netWeight'] ?? '0.000',
            'SaleType'                            => $item['putAway'] == 'UP' ? 0 : 1,
            'SKUCode'                             => $skuRow['skuCode'],
            'CommodityArchivesID'                 => $supGoodsInfo['goods_id'],
            'HSCode'                              => $skuRow['hsCode'],
            'IsHaveTaxRate'                       => $item['freeTax'] == 'Y' ? 1 : 0,
            'UpstreamSaleType'                    => $item['putAway'] == 'UP' ? 1 : 0,
            'IsFreeShipping'                      => 1,//是否包邮 0 否 1 是
        ];
        SupplierCommodity::instance()->add($data);
        return ['supplier_goods_id' => $data['ID']];
    }

    /**
     * 处理商品主资料图片和详情信息
     * @param $goodsDetail
     */
    public function handleGoodsDetail($goodsDetail) {
        $ycGoodsDetail = CommodityDescription::instance()->info(['CommodityInfoID' => $goodsDetail['goods_id']]);
        if ($ycGoodsDetail) {
            //更新
            $update = [
                'PreDescription' => $ycGoodsDetail['Description'],
                'Description'    => $goodsDetail['desc'],
                'HasDes'         => $goodsDetail['hasDesc'],
                'Images'         => $goodsDetail['images'],
                'PreImages'      => $ycGoodsDetail['Images'],
                'HasImage'       => $goodsDetail['hasImage'],
                'UpdateTime'     => date('Y-m-d H:i:s')
            ];
            CommodityDescription::instance()->where('ID', $ycGoodsDetail['ID'])->update($update);
        } else {
            //新增
            $data = [
                'ID'              => IdService::instance()->getOtherID(),
                'Description'     => $goodsDetail['desc'],
                'HasDes'          => $goodsDetail['hasDesc'],
                'CommodityInfoID' => $goodsDetail['goods_id'],
                'Images'          => $goodsDetail['images'],
                'HasImage'        => $goodsDetail['hasImage'],
                'CreateTime'      => date('Y-m-d H:i:s')
            ];
            CommodityDescription::instance()->add($data);
        }
    }

    /**
     * 处理商品主资料信息
     * @param $skuRow
     * @param $item
     * @param $goodsBasic
     */
    public function handleGoodsBasic($skuRow, $item, $goodsBasic) {
        if (!empty($goodsBasic['brand_id']) && !empty($goodsBasic['third_class_id']) && $goodsBasic['country_id']
            && !empty($goodsBasic['images']) && !empty($goodsBasic['desc'])) {
            $is_complete = 1;
            $is_useable  = 1;
        } else {
            $is_complete = 0;
            $is_useable  = 0;
        }
        $skuCode = $skuRow['skuCode'];
        $ycGoods = CommodityArchives::instance()->info(['SKUCode' => $skuCode]);
        if ($ycGoods) {
            //更新
            $update = [
                'BD_ID'                  => $item['id'],
                'MarketPrice'            => $item['markingPrice'],
                'SkuExtraCode'           => $item['productCode'],
                'CountryID'              => $goodsBasic['country_id'],
                'UnitID'                 => $goodsBasic['unit_id'],
                'Name'                   => $skuRow['count'] > 1 ? $skuRow['upcName'] : $item['productName'],
                'BrandID'                => $goodsBasic['brand_id'],
                'SecondClassificationID' => $goodsBasic['second_class_id'],
                'ThirdClassificationID'  => $goodsBasic['third_class_id'],
                'SpuID'                  => $goodsBasic['spu_id'],
                'BD_SPU_ID'              => $skuRow['upcVo']['spu']['spuId'],
                'SpuStatus'              => 1,//spu属性状态 1-正常 0-禁用
                // 'SpuDefault' => ,//spu的默认商品 1-是 0-不是，同一spu只能存在一个1
                'SpecValue'              => $goodsBasic['spec_value_str'],//规格值,例(规格项id:规格项对应的规格值id;第二个规格项id:规格项对应的规格值id)(149204407:1063032784;149238345:27340449891)
                'SpuSpecJsonBody'        => $goodsBasic['value_name_str'],//spu规格的字符串，后台复显使用，例（红色，256G）
                'BarCode'                => $skuRow['upcVo']['upc'],
                'Weight'                 => $skuRow['upcVo']['grossWeight'] ?? '0.000',
                'CommodityType'          => $this->getGoodsType($skuRow['depot']['attribute']),
                'IsForbidden'            => $item['putAway'] == 'UP' ? 0 : 1,
                'IsDeleted'              => $item['delStatus'] == 'Y' ? 1 : 0,
                'IsIntegrity'            => $is_complete,
                'IsUseAble'              => $is_useable,
                'UpdateTime'             => date('Y-m-d H:i:s')
            ];
            CommodityArchives::instance()->where('ID', $ycGoods['ID'])->update($update);
            return ['goods_id' => $ycGoods['ID'], 'is_complete' => $is_complete];
        }
        //新增
        $data = [
            'ID'                      => IdService::instance()->getOtherID(),
            'BD_ID'                   => $item['id'],
            'MarketPrice'             => $item['markingPrice'],
            'SKUCode'                 => $skuCode,
            'SkuExtraCode'            => $item['productCode'],
            'CountryID'               => $goodsBasic['country_id'],
            'UnitID'                  => $goodsBasic['unit_id'],
            'Name'                    => $skuRow['count'] > 1 ? $skuRow['upcName'] : $item['productName'],
            'BrandID'                 => $goodsBasic['brand_id'],
            'SecondClassificationID'  => $goodsBasic['second_class_id'],
            'ThirdClassificationID'   => $goodsBasic['third_class_id'],
            'SpuID'                   => $goodsBasic['spu_id'],
            'BD_SPU_ID'               => $skuRow['upcVo']['spu']['spuId'],
            'SpuStatus'               => 1,//spu属性状态 1-正常 0-禁用
            // 'SpuDefault' => ,//spu的默认商品 1-是 0-不是，同一spu只能存在一个1
            'SpecValue'               => $goodsBasic['spec_value_str'],//规格值,例(规格项id:规格项对应的规格值id;第二个规格项id:规格项对应的规格值id)(149204407:1063032784;149238345:27340449891)
            'SpuSpecJsonBody'         => $goodsBasic['value_name_str'],//spu规格的字符串，后台复显使用，例（红色，256G）
            'BarCode'                 => $skuRow['upcVo']['upc'],
            'Weight'                  => $skuRow['upcVo']['grossWeight'] ?? '0.000',
            'CommodityType'           => $this->getGoodsType($skuRow['depot']['attribute']),
            'IsForbidden'             => $item['putAway'] == 'UP' ? 0 : 1,
            'IsDeleted'               => $item['delStatus'] == 'Y' ? 1 : 0,
            'FreightTemplateID'       => 1,
            'IsIntegrity'             => $is_complete,
            'IsUseAble'               => $is_useable,
            'ThirdPartyCrmLinkTime'   => date('Y-m-d H:i:s'),
            'ThirdPartyCrmLinkStatus' => 1,
            'ThirdPartyCrmContents'   => '默认绑定成功',
            'CreateTime'              => date('Y-m-d H:i:s')
        ];
        CommodityArchives::instance()->add($data);
        return ['goods_id' => $data['ID'], 'is_complete' => $is_complete];
    }

    /**
     * 处理spec和specValue
     * @param $skuRow
     */
    public function handleSpuSpec($skuRow) {
        $bdSpu          = $skuRow['upcVo']['spu'];
        $bdSpec         = $skuRow['upcVo']['upcAttrValueVOList'];
        $bdSpuId        = $bdSpu['spuId'];
        $ycSpecAttrIds  = [];
        $ycSpecValueArr = [];
        $ycValueNameArr = [];
        foreach ($bdSpec as $spec) {
            $ycSpec = CommoditySpecAttr::instance()->info(['BD_ID' => $spec['attrId']]);
            if ($ycSpec) {
                //更新spec
                $update = [
                    'SpuExtraID' => $bdSpuId,
                    'AttrName'   => addslashes($spec['attrName']),
                    'UpdateTime' => date('Y-m-d H:i:s')
                ];
                CommoditySpecAttr::instance()->where('ID', $ycSpec['ID'])->update($update);
                $ycSpecId = $ycSpec['ID'];
            } else {
                //新增spec
                $data = [
                    'ID'         => IdService::instance()->getOtherID(),
                    'BD_ID'      => $spec['attrId'],
                    'SpuExtraID' => $bdSpuId,
                    'IsDeleted'  => 0,
                    'CreateTime' => date('Y-m-d H:i:s'),
                    'AttrName'   => addslashes($spec['attrName']),
                ];
                CommoditySpecAttr::instance()->add($data);
                $ycSpecId = $data['ID'];
            }
            array_push($ycSpecAttrIds, $ycSpecId);
            $ycSpecValue = CommoditySpecValue::instance()->info(['BD_ID' => $spec['attrValueId']]);
            if ($ycSpecValue) {
                //更新specValue
                $update = [
                    'SpecID'     => $ycSpecId,
                    'ValueName'  => $spec['attrValueName'],
                    'UpdateTime' => date('Y-m-d H:i:s')
                ];
                CommoditySpecValue::instance()->where('ID', $ycSpecValue['ID'])->update($update);
                array_push($ycSpecValueArr, "{$ycSpecId}:{$ycSpecValue['ID']}");
            } else {
                //新增specValue
                $data = [
                    'ID'         => IdService::instance()->getOtherID(),
                    'BD_ID'      => $spec['attrValueId'],
                    'IsDeleted'  => 0,
                    'CreateTime' => date('Y-m-d H:i:s'),
                    'SpecID'     => $ycSpecId,
                    'ValueName'  => $spec['attrValueName'],
                ];
                CommoditySpecValue::instance()->add($data);
                array_push($ycSpecValueArr, "{$ycSpecId}:{$data['ID']}");
            }
            array_push($ycValueNameArr, $spec['attrValueName']);
        }
        $ycSpecValueStr = $ycSpecValueArr ? implode(";", $ycSpecValueArr) : '';
        $ycValueNameStr = $ycValueNameArr ? implode(",", $ycValueNameArr) : '';
        return ['spec_attr_ids' => $ycSpecAttrIds, 'spec_value_str' => $ycSpecValueStr, 'value_name_str' => $ycValueNameStr];
    }

    /**
     * 处理group_attr
     * @param $groupAttr
     */
    public function handleGroupAttr($groupAttr) {
        foreach ($groupAttr['spec_attr_ids'] as $spec_attr_id) {
            $where       = [
                ['GroupID', '=', $groupAttr['spec_group_id']],
                ['AttrID', '=', $spec_attr_id]
            ];
            $ycGroupAttr = CommodityGroupAttr::instance()->info($where);
            if ($ycGroupAttr) {
                continue;
            }
            $data = [
                'ID'         => IdService::instance()->getOtherID(),
                'GroupID'    => $groupAttr['spec_group_id'],
                'AttrID'     => $spec_attr_id,
                'CreateTime' => date('Y-m-d H:i:s'),
                'IsDeleted'  => 0,
            ];
            CommodityGroupAttr::instance()->add($data);
        }
    }

    /**
     * 处理spec_group
     * @param $skuRow
     * @param $specGroup
     */
    public function handleSpecGroup($skuRow, $specGroup) {
        $bdSpu       = $skuRow['upcVo']['spu'];
        $bdSpec      = $skuRow['upcVo']['upcAttrValueVOList'];
        $bdSpuId     = $bdSpu['spuId'];
        $groupName   = implode('-', array_column($bdSpec, 'attrName')) . "（{$bdSpu['spuName']}）";
        $where       = [
            ['SpuID', '=', $specGroup['spu_id']],
            ['SpuExtraID', '=', $bdSpuId]
        ];
        $ycSpecGroup = CommoditySpecGroup::instance()->info($where);
        if ($ycSpecGroup) {
            //更新
            $update = [
                'GroupName'  => addslashes($groupName),
                'ClassID'    => $specGroup['third_class_id'],
                'UpdateTime' => date('Y-m-d H:i:s')
            ];
            CommoditySpecGroup::instance()->where('ID', $ycSpecGroup['ID'])->update($update);
            return ['spec_group_id' => $ycSpecGroup['ID']];
        }
        $data = [
            'ID'         => IdService::instance()->getOtherID(),
            'SpuExtraID' => $bdSpuId,
            'SpuID'      => $specGroup['spu_id'],
            'ClassID'    => $specGroup['third_class_id'],
            'GroupName'  => addslashes($groupName),
            'CreateTime' => date('Y-m-d H:i:s'),
        ];
        CommoditySpecGroup::instance()->add($data);
        return ['spec_group_id' => $data['ID']];
    }

    /**
     * 处理SPU
     * @param $skuRow
     */
    public function handleSpu($skuRow) {
        $bdSpu = $skuRow['upcVo']['spu'];
        // $ycSpu = CommoditySpu::instance()->info(['ExtraID' => $bdSpu['spuId']]);
        $ycSpu = CommoditySpu::instance()->info(['SpuName' => addslashes($bdSpu['spuName'])]);
        if ($ycSpu) {
            //更新
            $update = [
                'SpuCode'    => 'SP' . IdService::instance()->getOtherID(),
                'SpuName'    => addslashes($bdSpu['spuName']),
                'UpdateTime' => date('Y-m-d H:i:s')
            ];
            CommoditySpu::instance()->where('ID', $ycSpu['ID'])->update($update);
            return ['spu_id' => $ycSpu['ID']];
        }
        //新增
        $data = [
            'ID'         => IdService::instance()->getOtherID(),
            'ExtraID'    => $bdSpu['spuId'],
            'IsDeleted'  => 0,
            'CreateTime' => date('Y-m-d H:i:s'),
            'SpuCode'    => 'SP' . IdService::instance()->getOtherID(),
            'SpuName'    => addslashes($bdSpu['spuName']),
        ];
        CommoditySpu::instance()->add($data);
        return ['spu_id' => $data['ID']];
    }

    /**
     * 处理图片和详情
     * @param $skuList
     */
    public function formatImgAndDesc($skuList) {
        $bdImg  = $skuList['mainImgList'];
        $bdDesc = $skuList['detailImgList'];
        $ycImgs = [];
        foreach ($bdImg as $k => $img) {
            $ycImgs[] = [
                'ImageUrl' => $img['imgUrl'],
                'IsMain'   => $k == 0 ? 1 : 0,
            ];
        }
        $html = '';
        foreach ($bdDesc as $desc) {
            $html .= '<p><img src="' . $desc['imgUrl'] . '" style="max-width:100%;" contenteditable="false" alt=""/></p>';
        }
        return [
            'hasImage' => $ycImgs ? 1 : 0,
            'images'   => json_encode($ycImgs, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'hasDesc'  => $html ? 1 : 0,
            'desc'     => $html
        ];
    }

    /**
     * 处理分类
     * @param $skuList
     */
    public function handleClass($skuList) {
        $bdSecondClass = $skuList['mainCategory'];//一级分类 对应云仓 二级分类
        $bdThirdClass  = $skuList['secondCategory'];//二级分类 对应云仓 三级分类
        // 二级
        $ycSecondClass = Classifyinfo::where('ExtraID', $bdSecondClass['cid'])->where('Level', 2)->first();
        $ycSecondClass = empty($ycSecondClass) ? [] : $ycSecondClass->toArray();
        $second_class_id  = 0;
        $second_class_name = '';
        
        if ($ycSecondClass) {
            //二级分类更新
            $secondUpdate = [
                'ClassificationCode' => $bdSecondClass['crmCategory'],
                'ParentID'           => '834753927676612609',//固定的
                'ClassificationName' => $bdSecondClass['categoryName'],
                'Image'              => $bdSecondClass['categoryLogo'],
                'UpdateTime'         => date('Y-m-d H:i:s')
            ];
            Classifyinfo::instance()->where('ID', $ycSecondClass['ID'])->update($secondUpdate);
            $second_class_id   = $ycSecondClass['ID'];
            $second_class_name = $ycSecondClass['ClassificationName'];
        } else {
            //不进行新增了
           /*  //二级分类新增
            $secondData = [
                'ID'                 => IdService::instance()->getOtherID(),
                'ExtraID'            => $bdSecondClass['cid'],
                'IsDeleted'          => 0,
                'CreateTime'         => date('Y-m-d H:i:s'),
                'TaxRate'            => '0.000',
                'Level'              => 2,
                'IsForbidden'        => 0,
                'ClassificationCode' => $bdSecondClass['crmCategory'],
                'ParentID'           => $bdSecondClass['parentId'],
                'ClassificationName' => $bdSecondClass['categoryName'],
                'Image'              => $bdSecondClass['categoryLogo'],
                'IsNotShow'          => 0,
            ];
            Classifyinfo::instance()->add($secondData);
            $second_class_id   = $secondData['ID'];
            $second_class_name = $secondData['ClassificationName']; */
        }
        
        //三级
        $ycThirdClass = Classifyinfo::where('ExtraID', $bdThirdClass['cid'])->where('Level', 3)->first();
        $ycThirdClass = empty($ycThirdClass) ? [] : $ycThirdClass->toArray();
        $third_class_id = 0;
        $third_class_name = '';
        if ($ycThirdClass) {
            //三级分类更新
            $secondUpdate = [
                'ClassificationCode' => $bdThirdClass['crmCategory'],
                // 'ParentID'           => $bdThirdClass['parentId'],
                'ParentID'           => $second_class_id,
                'ClassificationName' => $bdThirdClass['categoryName'],
                'Image'              => $bdThirdClass['categoryLogo'],
                'UpdateTime'         => date('Y-m-d H:i:s')
            ];
            Classifyinfo::instance()->where('ID', $ycThirdClass['ID'])->update($secondUpdate);
            $third_class_id   = $ycThirdClass['ID'];
            $third_class_name = $ycThirdClass['ClassificationName'];
        } else {
            /* //三级分类新增
            $thirdData = [
                'ID'                 => IdService::instance()->getOtherID(),
                'ExtraID'            => $bdThirdClass['cid'],
                'IsDeleted'          => 0,
                'CreateTime'         => date('Y-m-d H:i:s'),
                'TaxRate'            => '0.000',
                'Level'              => 3,
                'IsForbidden'        => 0,
                'ClassificationCode' => $bdThirdClass['crmCategory'],
                // 'ParentID'           => $bdThirdClass['parentId'],
                'ParentID'           => $second_class_id,
                'ClassificationName' => $bdThirdClass['categoryName'],
                'Image'              => $bdThirdClass['categoryLogo'],
                'IsNotShow'          => 0,
            ];
            Classifyinfo::instance()->add($thirdData);
            $third_class_id   = $thirdData['ID'];
            $third_class_name = $thirdData['ClassificationName']; */
        }
        return [
            'second_class_id'   => $second_class_id,
            'second_class_name' => $second_class_name,
            'third_class_id'    => $third_class_id,
            'third_class_name'  => $third_class_name
        ];
    }

    /**
     * 处理单位
     * @param $skuRow
     */
    public function handleUnit($skuRow) {
        $bdUnit = $skuRow['upcVo']['unit'];
        $ycUnit = Unitinfo::instance()->info(['ExtraID' => $bdUnit['unitId']]);
        if ($ycUnit) {
            //更新
            $update = [
                'Name'       => $bdUnit['unitName'] ??'',
                'UnitCode'   => $bdUnit['unitCode'] ??'',
                'UpdateTime' => date('Y-m-d H:i:s')
            ];
            Unitinfo::instance()->where('ID', $ycUnit['ID'])->update($update);
            return ['unit_id' => $ycUnit['ID'], 'unit_name' => $bdUnit['unitName'] ??''];
        }
        //新增
        $data = [
            'ID'           => IdService::instance()->getOtherID(),
            'ExtraID'      => $bdUnit['unitId'],
            'IsDeleted'    => 0,
            'CreateUserID' => 0,
            'CreateTime'   => date('Y-m-d H:i:s'),
            'Name'         => $bdUnit['unitName']??'',
            'UnitCode'     => $bdUnit['unitCode'] ??'',
        ];
        Unitinfo::instance()->add($data);
        return ['unit_id' => $data['ID'], 'unit_name' => $bdUnit['unitName']??''];
    }

    /**
     * 处理国家
     * @param $skuRow
     */
    public function handleCountry($skuRow) {
        $bdCountry = $skuRow['upcVo']['country'];
        $ycCountry = Countryinfo::instance()->info(['ExtraID' => $bdCountry['countryId']]);
        if ($ycCountry) {
            //更新
            $update = [
                'CountryCode'         => !empty($bdCountry['code']) ? $bdCountry['code'] : '',
                'CountryAbbreviation' => $bdCountry['countryNameEn'],
                'CountryName'         => !empty($bdCountry['countryName']) ? $bdCountry['countryName'] : '暂无',
                'UpdateTime'          => date('Y-m-d H:i:s')
            ];
            Countryinfo::instance()->where('ID', $ycCountry['ID'])->update($update);
            return ['country_id' => $ycCountry['ID'], 'country_name' => $bdCountry['countryName']];
        }
        //新增
        $data = [
            'ID'                  => IdService::instance()->getOtherID(),
            'ExtraID'             => $bdCountry['countryId'],
            'IsDeleted'           => 0,
            'CreateUserID'        => 0,
            'CreateTime'          => date('Y-m-d H:i:s'),
            'OrderInt'            => 0,
            'CountryCode'         => !empty($bdCountry['code']) ? $bdCountry['code'] : '',
            'CountryAbbreviation' => $bdCountry['countryNameEn'],
            'CountryName'         => !empty($bdCountry['countryName']) ? $bdCountry['countryName'] : '暂无',
            'Image'               => '',
            'IsShow'              => 1,
        ];
        Countryinfo::instance()->add($data);
        return ['country_id' => $data['ID'], 'country_name' => $bdCountry['countryName']];
    }

    /**
     * 处理品牌
     * @param $skuRow
     */
    public function handleBrand($skuRow) {
        $bdBrand = $skuRow['upcVo']['brand'];
        $ycBrand = Brandinfo::instance()->info(['ExtraID' => $bdBrand['brandId']]);
        if ($ycBrand) {
            //更新
            $update = [
                'BrandCode'        => $bdBrand['brandId'],
                'Abbreviation'     => $bdBrand['brandNameEn'],
                'BrandName'        => $bdBrand['brandNameCn'] ??'其他',
                'BrandFirstLetter' => strtoupper(mb_substr($bdBrand['brandNameEn'], 0, 1)),
                'Image'            => $bdBrand['logo'],
                'Banner'           => $bdBrand['logo'],
                'UpdateTime'       => date('Y-m-d H:i:s')
            ];
            Brandinfo::instance()->where('ID', $ycBrand['ID'])->update($update);
            return ['brand_id' => $ycBrand['ID'], 'brand_name' => $bdBrand['brandNameCn']];
        }
        //新增
        $data = [
            'ID'               => IdService::instance()->getOtherID(),
            'ExtraID'          => $bdBrand['brandId'],
            'IsDeleted'        => 0,
            'CreateTime'       => date('Y-m-d H:i:s'),
            'OrderInt'         => 0,
            'BrandCode'        => $bdBrand['brandId'],
            'Abbreviation'     => $bdBrand['brandNameEn'],
            'BrandName'        => $bdBrand['brandNameCn'] ??'其他',
            'BrandFirstLetter' => strtoupper(mb_substr($bdBrand['brandNameEn'], 0, 1)),
            'Image'            => $bdBrand['logo'],
            'Banner'           => $bdBrand['logo'],
            'IsShow'           => 1,
        ];
        Brandinfo::instance()->add($data);
        return ['brand_id' => $data['ID'], 'brand_name' => $bdBrand['brandNameCn'] ??'组合商品品牌'];
    }

    /**
     * 处理供应商和仓库
     * @param $skuRow
     */
    public function handleWarehouseAndSupplierCompany($skuRow) {
        $wareHouse = $skuRow['depot'];
        $wh        = WarehouseInfo::instance()->info(['WarehouseCode' => $wareHouse['depotCode']]);
        if ($wh) {
            return ['warehouse_id' => $wh['ID'], 'supplier_id' => $wh['SupplierID']];
        }
        //判断是否存在供应商
        $sc1 = SupplierCompany::instance()->info(['SupplierCode' => $wareHouse['supplierCode']]);
        if ($sc1) {
            //供应商存在 只需要新增仓库
            $warehouse_id = IdService::instance()->getOtherID();
            $wh_data      = [
                'ID'               => $warehouse_id,
                'WarehouseAccount' => $wareHouse['supplierCode'] . '-' . $wareHouse['depotCode'],
                'WarehouseType'    => 0,
                'ExamineState'     => 1,
                'SupplierID'       => $sc1['ID'],
                'WarehouseCode'    => $wareHouse['depotCode'],
                'WarehouseName'    => $wareHouse['depotName'],
                'CanModifyStock'   => 1,
                'CanModifyPrice'   => 1,
                'IsCombineOrders'  => 1,
                'CreateTime'       => date('Y-m-d H:i:s'),
                'IsDeleted'        => 0,
                'JsonBody'         => json_encode([]),
            ];
            WarehouseInfo::instance()->add($wh_data);
            return ['warehouse_id' => $warehouse_id, 'supplier_id' => $sc1['ID']];
        }
        // 供应商编码拼接仓库编码去查询供应商是否存在   SU200317134338005005-DF/ZY/40
        $mixSupplierCode = $wareHouse['supplierCode'] . '-' . $wareHouse['depotCode'];
        $sc2             = SupplierCompany::instance()->info(['SupplierCode' => $mixSupplierCode]);
        if ($sc2) {
            //供应商存在 只需要新增仓库
            $warehouse_id = IdService::instance()->getOtherID();
            $wh_data      = [
                'ID'               => $warehouse_id,
                'WarehouseAccount' => $wareHouse['supplierCode'] . '-' . $wareHouse['depotCode'],
                'WarehouseType'    => 0,
                'ExamineState'     => 1,
                'SupplierID'       => $sc2['ID'],
                'WarehouseCode'    => $wareHouse['depotCode'],
                'WarehouseName'    => $wareHouse['depotName'],
                'CanModifyStock'   => 1,
                'CanModifyPrice'   => 1,
                'IsCombineOrders'  => 1,
                'CreateTime'       => date('Y-m-d H:i:s'),
                'IsDeleted'        => 0,
                'JsonBody'         => json_encode([]),
            ];
            WarehouseInfo::instance()->add($wh_data);
            return ['warehouse_id' => $warehouse_id, 'supplier_id' => $sc2['ID']];
        }
        //仓库和供应商都需要新增
        $bdSupplier  = $skuRow['supplier'];
        $supplier_id = IdService::instance()->getOtherID();
        $payDeclare  = 0;
        if (!empty($wareHouse['attribute']) && in_array($wareHouse['attribute'], ['5', '6', '7'])) {
            $payDeclare = 1;
        }
        $supplier_data = [
            'ID'                     => $supplier_id,
            'SupplierName'           => $bdSupplier['supplierName'],
            'SupplierCode'           => $bdSupplier['supplierCode'] . '-' . $wareHouse['depotCode'],
            'CompanyStatus'          => 1,
            'SettlementMethod'       => 1,
            'OrderDeclare'           => 0,
            'PayDeclare'             => $payDeclare,
            'OrderDockMode'          => 1,
            'IsOpenSupplierSettleIn' => 0,
            'ShowInPreferred'        => 1,
            'SupplierAlias'          => "{$bdSupplier['supplierName']}({$wareHouse['depotName']})",
            'CreateTime'             => date('Y-m-d H:i:s'),
            'IsDeleted'              => 0
        ];
        SupplierCompany::instance()->add($supplier_data);
        //供应商存在 只需要新增仓库
        $warehouse_id = IdService::instance()->getOtherID();
        $wh_data      = [
            'ID'               => $warehouse_id,
            'WarehouseAccount' => $wareHouse['supplierCode'] . '-' . $wareHouse['depotCode'],
            'WarehouseType'    => 0,
            'ExamineState'     => 1,
            'SupplierID'       => $supplier_id,
            'WarehouseCode'    => $wareHouse['depotCode'],
            'WarehouseName'    => $wareHouse['depotName'],
            'CanModifyStock'   => 1,
            'CanModifyPrice'   => 1,
            'IsCombineOrders'  => 1,
            'CreateTime'       => date('Y-m-d H:i:s'),
            'IsDeleted'        => 0,
            'JsonBody'         => json_encode([]),
        ];
        WarehouseInfo::instance()->add($wh_data);
        return ['warehouse_id' => $warehouse_id, 'supplier_id' => $supplier_id];
    }

    /**
     * 获取商品类型
     * @param $goodsType
     */
    public function getGoodsType($goodsType) {
        if (in_array($goodsType, ['1', '5'])) {
            return 1;
        } else if (in_array($goodsType, ['2', '6'])) {
            return 0;
        } else if (in_array($goodsType, ['3', '4', '7'])) {
            return 2;
        } else {
            return 0;
        }
    }
}